﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace chatgpt_LKZ4251
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public GPTConfig Config;

        private byte[] l;

        private Random random;

        private long id;

        private static string DefaultTitle = "chagpt-木子李(此工具由木子李提供，使用了3.5GPT接口实现，可以联合上下文提问！联系方式：wx LKZ4251)";
        public MainWindow()
        {
            InitializeComponent();
            this.Config = new GPTConfig();
            this.DataContext = this.Config;
            this.l = new byte[10240];
            this.random = new Random();
            this.id = this.random.Next();
            this.Title = DefaultTitle;
        }

        private void HTTPRequestGPT1()
        {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://api.aichatos.cloud/api/generateStream"));
            httpWebRequest.Method = "POST";
            httpWebRequest.Accept = "application/json, text/plain, */*";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            httpWebRequest.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            httpWebRequest.Headers.Add("Origin", "https://dev.yqcloud.top");
            httpWebRequest.Headers.Add("Aec-ch-ua", "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not: A - Brand\";v=\"99\"");
            httpWebRequest.Headers.Add("Sec-Ch-Ua", "\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Google Chrome\";v=\"114\"");
            httpWebRequest.Headers.Add("Sec-Ch-Ua-Mobile", "?0");
            httpWebRequest.Headers.Add("Sec-ch-ua-platform", "\"Windows\"");
            httpWebRequest.Headers.Add("Sec-Fetch-Dest", "empty");
            httpWebRequest.Headers.Add("Sec-Fetch-Mode", "cors");
            httpWebRequest.Headers.Add("Sec-Fetch-Site", "cross-site");
            httpWebRequest.Referer = "https://dev.yqcloud.top/";
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36";
            httpWebRequest.Host = "api.aichatos.cloud";
            Stream requestStream = httpWebRequest.GetRequestStream();
            string text = " {\"prompt\":\"" + this.Config.Question + "\",\"userId\":\"#/chat/" + id + "\",\"network\":true,\"system\":\"\",\"withoutContext\":false,\"stream\":false}";
            //JObject val = JObject.Parse(text);
            //val["prompt"] = JToken.op_Implicit(content);
            //text = ((object)val).ToString();
            byte[] bytes = Encoding.UTF8.GetBytes(text);
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Dispose();
            WebResponse response = httpWebRequest.GetResponse();
            Stream responseStream = response.GetResponseStream();
            int num = 0;
            int num2 = 0;
            int num3 = 0;
            this.Config.History += $"\nChatGPT:\n";
            do
            {
                this.Dispatcher.Invoke(new Action(() => 
                {
                    num2 = responseStream.Read(l, num, 10240 - num);
                    num += num2;
                    if (num - num3 >= 3)
                    {
                        this.Config.History += Encoding.UTF8.GetString(l, num3, num - num3);
                        this.sv.ScrollToBottom();
                        num3 += num - num3;
                    }
                }));
                Thread.Sleep(10);
            }
            while (num2 != 0);
            this.Config.History += "\n";
            this.Config.Question = string.Empty;

            this.Dispatcher.Invoke(new Action(delegate
            {
                this.tbQ.IsReadOnly = false;
                this.btnNew.IsEnabled = this.btnClear.IsEnabled = this.btnSend.IsEnabled = true;
                this.Title = DefaultTitle;
                this.tbQ.Focus();
            }));
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            this.sendQuestion();
        }

        private void tbQ_KeyDown(object sender, KeyEventArgs e)
        {
           if (e.Key == Key.Enter)
           {
                this.sendQuestion();
           }
        }

        private void sendQuestion()
        {
            if (string.IsNullOrEmpty(this.Config.Question)) return;
            this.Focus();
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            this.Config.History += $"\n你：\n{this.Config.Question}\n";
            this.tbQ.IsReadOnly = true;
            this.btnNew.IsEnabled = this.btnClear.IsEnabled = this.btnSend.IsEnabled = false;
            this.Title = "ChatGPT回答中，请稍候";
            Thread thread = new Thread(new ThreadStart(HTTPRequestGPT1));
            thread.IsBackground = true;
            thread.Start();
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if(MessageBox.Show("您确定要清空吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                this.Config.History = string.Empty;
            }
        }

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("开始新的对话后上下文将被清空，您确定继续吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                this.Config.History = string.Empty;
                this.id = random.Next();
            }
        }
    }
}
